import {messages} from "share/common";
import React from 'react'
import {connect} from 'react-redux'
import { Form, Modal, Button, message, Select, Spin, Radio } from 'antd'
import proxiesService from 'components/template/proxies/proxies-service'
import expenseReportService from 'containers/expense-report/expense-report.service'
import Selector from 'components/selector'
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;

class Proxies extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isShowProxyButton: false,
      isShowProxyModal: false,
      buttonContent: '',
      userJobsDTOs: [],
      id: '',
      userOID: '',
      fetched: false,
      loading: false,
      formOption: [],
      forWhom: 'forBoss', // “代上级”：forBoss “代司机”：forDriver 用户要代提报销单，需要先选择被代替人的身份，选择结果影响了“申请人”的数据源，最后决定了“单据名称”的数据源
      agent: 'forBoss' // 申请人的数据源
    };
  }

  componentWillMount() {
    this.getIsProxyCustomForm();
    const {formType} = this.props;
    this.setButtonContent(formType);
  }

  componentWillReceiveProps(nextProps) {
    this.setButtonContent(nextProps.formType);
  }

  setButtonContent(type) {
    let buttonContent = '';
    switch (type) {
      case '102':
        buttonContent = messages('components.key671');
        break;
      case '101':
        buttonContent = messages('components.key672');
        break;
      case '104':
        buttonContent = messages('components.key710')/*代理借款单*/;
        break;
      default :
        buttonContent = messages('components.key671');
        break;
    }
    this.setState({buttonContent});
  };

  /**
   * 是否有代替
   * 2020-11-24 报销单、申请单、借款单的代提按钮是否显示由当前登录用户是否是秘书组成员决定
   */
  async getIsProxyCustomForm() {
    const res = await expenseReportService.ifShowProxies();
    if (res.status === 200) {
      this.setState({
        isShowProxyButton: res.data
      });
    }
    // proxiesService.getIsProxyCustomForm(this.props.formType).then((res) => {
    //   this.setState({ isShowProxyButton: res.data });
    // })
  };

  //申请人改变
  // 2020-11-23 报销单--代提报销单的“单据名称”由“代上级”或“代司机”和申请人决定
  changeAgent = (value) => {
    if (!value || value.length === 0) {
      return false
    }
    const { formType } = this.props;
    let userOID = null;
    if (this.state.forWhom === 'forBoss') {
      userOID = value
    } else if (this.state.forWhom === 'forDriver') {
      if (value && value.length > 0) {
        userOID = value.split(',')[1]
      } else {
        userOID = ''
      }
    }
    console.log('userOID', userOID)
    this.setState({ userOID: userOID, id: '' }, () => {
      const { userOID } = this.state;
      this.props.form.resetFields(['formOID','jobId']);
      userOID && this.setState({ loading: true });
      if (this.state.forWhom === 'forBoss') {
        userOID && proxiesService.getJobs(userOID).then(res => {
          let temp = [];
          res.data.companyWithUserJobsDTOList && res.data.companyWithUserJobsDTOList.map(item => {
            item.userJobsDTOList.map(it => {
              temp.push(it);
            })
          });
          this.setState({ userJobsDTOs: temp }, () => {
            const { userJobsDTOs, forWhom, agent } = this.state;
            if (userJobsDTOs.length === 1) {
              // 代提表单-单据名称 由“代司机”/“代上级”和“申请人决定”，司机的“单据名称”由前者决定，上司的由二者同时决定
              let param = {
                formType, 
                userOID,
                applicationFormType: this.props.type
              }
              if (formType === '101') { // 申请单
                param.isAll = this.props.isAll
              } else if (formType === '102') { // 报销单
                const proxyType = forWhom === 'forDriver' ? 1 : forWhom === 'forBoss' ? 2 : null
                param.proxyType = proxyType
              }
              proxiesService.getProxyMyForms({...param}).then(res => {
                this.setState({ formOption: res.data, loading: false });
              })
            } else {
              this.setState({ loading: false });
            }
          })
        }).catch(e => {
          this.setState({ loading: false });
          message.error(e.response.data.message);
        });
      } else if (this.state.forWhom === 'forDriver') {
        const param = { 
          proxyType: 1, 
          formType, 
          userOID,
          applicationFormType: this.props.type
        }

        proxiesService.getProxyMyForms({...param}).then(res => {
          this.setState({ formOption: res.data, loading: false });
        })
      }
      
    })
  };

  //取消弹框
  modalControl = (flag) => {
    this.setState({
      isShowProxyModal: flag
    })
  };

  //确认单据
  onOK = () => {
    const { validateFieldsAndScroll } = this.props.form,
      { onOk, user } = this.props,
      { userJobsDTOs, forWhom } = this.state;
    validateFieldsAndScroll((err, value) => {
      // console.log('this.props.user', this.props.user)
      if (!err) {
        this.modalControl(false);
        if (forWhom === 'forDriver') {
          let driverAndSuperior = value.agent || ''; // 结构：司机id,审批人oid
          let driverId = '';
          let superiorOID = '';
          let driverVerdor = '';
          if (driverAndSuperior.length > 0) {
            const driverInfo = driverAndSuperior.split(',')
            superiorOID = driverInfo[1] // 审批人oid
            driverId = driverInfo[0]; // 司机id
            driverVerdor = driverInfo[2] // 司机的vendor
          }
          if (superiorOID && superiorOID.length > 0) {
            onOk(value.formOID, ':applicantJobId', superiorOID, true, driverId, driverVerdor)
          }
        } else {
          onOk(value.formOID, value.jobId || userJobsDTOs[0].id, value.agent, true, null)
        }
      }
    })
  };

  handleChangeJob = key => {
    this.setState({ id: key }, () => {
      const { formType } = this.props;
      this.props.form.resetFields(['formOID']);
      this.setState({ fetched: true });
      const param = { 
        formType, 
        jobId: this.state.id, 
        applicationFormType: this.props.type
      }

      if (this.state.forWhom === 'forDriver') {
        param.proxyType = 1
        param.userOID = this.state.userOID
      }
      proxiesService.getProxyMyForms({...param}).then(res => {
        this.setState({formOption: res.data, fetched: false});
      }).catch(e => {
        this.setState({ fetched: false });
        message.error(e.response.data.message);
      })
    })
  };

  joinJob = item => {
    let res = [];
    item.position && res.push(item.position);
    item.companyName && res.push(item.companyName);
    item.departmentName && res.push(item.departmentName);
    item.duty && res.push(item.duty);
    item.rank && res.push(item.rank);
    return res.join(' - ');
  };

  handleCancel = () => {
    const { resetFields } = this.props.form;
    resetFields();
    this.setState({
      isShowProxyModal: false,
      userOID: '',
      userJobsDTOs: []
    })
  };

  /**
   * 用户选择“代上级”、“代司机”发生变化时触发，直接影响了申请人的数据源
   * @param {Object} e
   */
  handleOnChooseForWhom = (e) => {
    this.props.form.setFieldsValue({agent: null});
    if (e.target.value === 'forBoss') {
      this.setState({
        userOID: '',
        formOption: [],
        forWhom: e.target.value,
        agent: 'forBoss'
      })
    } else if (e.target.value === 'forDriver') {
      this.setState({
        userOID: '',
        formOption: [],
        forWhom: e.target.value,
        agent: 'forDriver'
      })
    }
  }

  render() {
    const {formType} = this.props;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { isShowProxyButton, isShowProxyModal, userOID, buttonContent, userJobsDTOs,
      id, fetched, formOption, loading, agent } = this.state;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14, offset: 1},
    };
    console.log('agent', agent);
    const userFrom = agent === 'forDriver' ? 1 : agent === 'forBoss' ? 2 : null
    // console.log('userFrom', userFrom)
    return (
      <span>
        {isShowProxyButton && <Button onClick={() => this.modalControl(true)}>
          {buttonContent}
        </Button>}
        <Modal
          title={buttonContent}
          visible={isShowProxyModal}
          width={600}
          footer={[
            <Button key="cancel" onClick={this.handleCancel}>{messages('common.cancel')}</Button>,
            <Button key="ok" type="primary" disabled={!getFieldValue('formOID')} onClick={this.onOK}>{messages('common.ok')}</Button>
          ]}
          onCancel={this.handleCancel}
        >
          <Spin spinning={loading}>
            <Form>
              {/** 代提报销单可以选择是“代上级”还是“代司机”，申请单和借款单的代提只有“代上级” */}
              <FormItem {...formItemLayout} label={'代谁'}>
                <RadioGroup value={this.state.forWhom} onChange={(e) => this.handleOnChooseForWhom(e)}>
                  <RadioButton value={'forBoss'}>代上级</RadioButton>
                  {this.props.formType === '102' ? <RadioButton value={'forDriver'}>代司机</RadioButton> : null}
                </RadioGroup>
              </FormItem>
              {
                this.state.agent.length > 0 ?
                  agent === 'forBoss' ?
                    <FormItem key={'forBoss'} {...formItemLayout} label={messages('common.applicant') /*申请人*/}>
                      {getFieldDecorator('agent', {
                        rules: [{
                          required: true,
                          message: messages('common.please.select')/*请选择*/
                        }]
                      })(<Selector
                          showSearch={true}
                          onChange={this.changeAgent}
                          placeholder={messages('common.please.select') /*'请输入选择'*/}
                          type={'forBoss'}
                        />)}
                      </FormItem> :
                      <FormItem key={'forDriver'} {...formItemLayout} label={messages('common.applicant') /*申请人*/}>
                        {getFieldDecorator('agent', {
                          rules: [{
                            required: true,
                            message: messages('common.please.select')/*请选择*/
                          }]
                        })(<Selector
                            showSearch={true}
                            onChange={this.changeAgent}
                            placeholder={messages('common.please.select') /*'请输入选择'*/}
                            type={'forDriver'}
                        />)}
                      </FormItem> : null
              }
              {
                userJobsDTOs.length > 1 && <FormItem {...formItemLayout} label={messages('components.key992')/*岗位*/}>
                  {getFieldDecorator('jobId', {
                    rules: [{
                      required: true, message: messages('common.please.select')/*请选择*/
                    }]
                  })(
                    <Select
                      onChange={this.handleChangeJob}
                      style={{width: '100%'}}
                      placeholder={messages('common.please.select')/*请选择*/}
                      getPopupContainer={triggerNode => triggerNode.parentNode}
                    >
                      {userJobsDTOs.map(item => (
                        <Option key={item.id} style={{whiteSpace: 'unset'}}>
                          {this.joinJob(item)}
                          {item.companyMainPosition && (
                            <span>（<span style={{color: "#108ee9"}}>{messages('components.key993')/*主岗*/}</span>）</span>
                          )}
                        </Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              }
              {
                userOID && (userJobsDTOs.length === 1 || id || this.state.forWhom === 'forDriver') &&
                <FormItem {...formItemLayout} label={messages('common.document.name')/*单据名称*/}>
                  {getFieldDecorator('formOID', {
                    rules: [{
                      required: true,
                      message: messages('common.please.select')/*请选择*/
                    }]
                  })(
                    <Select style={{ width: '100%' }}
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                            notFoundContent={fetched ? <Spin size="small"/> : messages('components.key410'/*无匹配结果*/)}
                            placeholder={messages('common.please.select')/*请选择*/}>
                      {
                        formOption.map(item => {
                          return <Option key={item.formOID}>{item.formName}</Option>
                        })
                      }
                    </Select>
                  )}
                </FormItem>
              }
            </Form>
          </Spin>
        </Modal>
      </span>
    )
  }
}

Proxies.propTypes = {
  formType: React.PropTypes.string, //代理单据类型102.报销单；101.申请单,104借款单
  isAll: React.PropTypes.bool,
  type: React.PropTypes.number, // 申请单入口 1(申请及预订) 2(商务及礼品申请) 3(公务卡申请) 4(其他事项申请) 5(代理申请),代理申请单不需要代理
  onOk: React.PropTypes.func
};

Proxies.defaultProps = {
  formType: '102'
};

Proxies.contextTypes = {
  router: React.PropTypes.object
};

const WrappedProxies = Form.create()(Proxies);

function mapStateToProps(state) {
  return {
    user: state.login.loginUser
  }
}

export default connect(mapStateToProps)(WrappedProxies);
